<?php
/**
 * Description: 获取面试试卷列表
 * User: devforma
 * Date: 2016/11/14
 * Time: 10:25
 */

class GetInterviewPapers implements iController {

    const NUM_PER_PAGE = 15;

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        if (empty($queryArgs['page']) || filter_var($queryArgs['page'], FILTER_VALIDATE_INT) === false || $queryArgs['page'] <= 0) {
            return genOutput(1000);
        }

        //参数默认值
        if (empty($queryArgs['area_id']) || filter_var($queryArgs['area_id'], FILTER_VALIDATE_INT) === false)
            $queryArgs['area_id'] = 0;
        if (empty($queryArgs['year']) || filter_var($queryArgs['year'], FILTER_VALIDATE_INT) === false)
            $queryArgs['year'] = 0;
        if (empty($queryArgs['note_id']) || filter_var($queryArgs['note_id'], FILTER_VALIDATE_INT) === false)
            $queryArgs['note_id'] = 0;

        $list = [];

        $sql = 'SELECT * FROM `interview_papers` WHERE 1';

        //地区筛选
        if (!empty($queryArgs['area_id'])) {
            $queryArgs['area_id'] = $cmsdb->getVar('SELECT `id` FROM `interview_area_conf` WHERE `area_id`=:aid', [':aid' => $queryArgs['area_id']]);
            $sql .= ' AND `interview_area_id`='.$queryArgs['area_id'];
        }

        //年份筛选
        if (!empty($queryArgs['year'])) {
            $sql .= ' AND `year`='.$queryArgs['year'];
        }

        //知识点筛选
        if (!empty($queryArgs['note_id'])) {
            $paperIdStr = $this->getPapersByNote($queryArgs['note_id']);
            if (!empty($paperIdStr)) $paperIdStr = implode(',', $paperIdStr);
            $sql .= " AND `id` IN ({$paperIdStr})";
        }

        //排序及分页
        $start = ($queryArgs['page'] - 1) * self::NUM_PER_PAGE;
        $sql .= " ORDER BY `id` DESC LIMIT {$start}, ".self::NUM_PER_PAGE;

        $papers = (array)$cmsdb->getResults($sql);
        foreach ($papers as $paper) {
            $list[] = [
                'id' => (int)$paper->id,
                'name' => $paper->name
            ];
        }

        return genOutput(1, ['papers' => $list]);
    }

    /**
     * 通过知识点获取面试试卷
     *
     * @param int $noteId 知识点id
     * @return array
     */
    private function getPapersByNote($noteId) {
        global $cmsdb;

        $sql = 'SELECT DISTINCT(p.paper_id) FROM `interview_relation_paper_question` AS p INNER JOIN `interview_relation_note_question` AS n 
        ON p.question_id=n.question_id AND n.note_id=:nid';

        return (array)$cmsdb->getCol($sql, [':nid' => $noteId]);
    }
}